package cn.hfjava.kz.service.impl;

import cn.hfjava.kz.entity.vo.TreeSelectVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.hfjava.kz.entity.po.Permission;
import cn.hfjava.kz.service.PermissionService;
import cn.hfjava.kz.mapper.PermissionMapper;
import jakarta.annotation.Resource;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lds
 * @description 针对表【permissions(权限表)】的数据库操作Service实现
 * @createDate 2024-07-23 09:51:13
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission>
        implements PermissionService{

    @Resource
    private PermissionMapper permissionMapper;

    /**
     * 获取所有的权限
     */
    @Override
    public List<Permission> findAllPermission() {
        List<Permission> permList = permissionMapper.selectList(null);
        return permList;
    }

    /**
     * 构建权限树结构
     *
     * @param permList
     */
    @Override
    public List<Permission> buildPermissionTree(List<Permission> permList) {
        List<Permission> treeList = Lists.newArrayList();
        for (Permission curPerm : permList) {
            if(0 == curPerm.getPid()) {
                treeList.add(findChildren(curPerm, permList));
            }
        }
        return treeList;
    }

    /**
     * 获取权限树
     *
     * @return
     */
    @Override
    public List<Permission> listWithTree() {
        //QueryWrapper用于构建查询条件
        // 查询所有的菜单权限列表
        List<Permission> permList  = permissionMapper.selectList(null);

        // 查询一级菜单权限信息列表，即pid=0的菜单权限
        List<Permission> rootList = permList.stream()
                .filter(perm -> perm.getPid() == 0)
                .sorted(Comparator.comparingInt(e -> (e.getSort() == null ? 0 : e.getSort()))) //升序排序 值越小越靠前
                .collect(Collectors.toList());
        //组装菜单权限树
        rootList.forEach(root -> {
            // 查询根节点下所有的子节点集合
            List<Permission> childList = getChild(root, permList);
            root.setChildren(childList);
        });
        return rootList;
    }

    /**
     * 根据当前登录用户ID获取此用户所有菜单权限信息
     *
     * @param loginId 当前登录用户ID
     * @return
     */
    @Override
    public List<Permission> getMenuTree(Integer loginId) {
        List<Permission> menuPermsList = permissionMapper.getMenuPermsByUserId(loginId);
        for (Permission p : menuPermsList) {
            if(p.getPid() == 0){
                List<Permission> children = getChild(p, menuPermsList);
                p.setChildren(children);
            }
        }
        return menuPermsList;
    }



    /**
     * 根据菜单名称分页获取菜单权限列表
     * @param title    菜单名称
     * @return
     */
    @Override
    public List<Permission> findPermsTreeByName(String title) {
        LambdaQueryWrapper<Permission> where = new LambdaQueryWrapper<>();
        where.like(StringUtils.hasText(title.trim()),Permission::getTitle,title);
        List<Permission> allList = permissionMapper.selectList(where);
        allList.forEach(perm -> {
            if(perm.getPid() == 0){
                List<Permission> children = getChild(perm, allList);
                perm.setChildren(children);
            }
        });
        return allList;
    }

    /**
     * 获取下拉菜单的树形结构
     *
     * @return
     */
    @Override
    public List<TreeSelectVO> findTreeSelectTree() {
        List<TreeSelectVO> rootList = new ArrayList<>();
        LambdaQueryWrapper<Permission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Permission::getId,Permission::getTitle,Permission::getPid,Permission::getPath);
        List<Permission> permList = permissionMapper.selectList(queryWrapper);
        List<TreeSelectVO> treeSelectVOList = permList.stream().filter(perm -> perm.getPid() == 0)
                .map(perm -> {
                    TreeSelectVO treeSelectVO = new TreeSelectVO();
                    treeSelectVO.setLabel(perm.getTitle());
                    treeSelectVO.setValue(perm.getId());
                    List<TreeSelectVO> childList = getChildTreeSelect(perm, permList);
                    treeSelectVO.setNumber(childList.size());
                    treeSelectVO.setChildren(childList);
                    treeSelectVO.setPath(perm.getPath());
                    return treeSelectVO;
                }).collect(Collectors.toList());

        TreeSelectVO root = new TreeSelectVO("主类目", -1, treeSelectVOList.size());
        root.setChildren(treeSelectVOList);

        rootList.add(root);
        return rootList;
    }

    /**
     * 根据id删除菜单
     * @param id 菜单id
     */
    @Override
    public Boolean deleteMenuById(Integer id) {
        if(hasChildMenu(id)){
            return Boolean.FALSE;
        }
        permissionMapper.deleteById(id);
        return Boolean.TRUE;
    }


    // 判断当前菜单是否有子菜单
    private boolean hasChildMenu(Integer id) {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid", id);
        Long count = permissionMapper.selectCount(queryWrapper);
        return count > 0L;
    }

    /**
     * 根据父级ID获取子级菜单权限列表
     * @param perm 当前节点对象
     * @param permList 所有菜单权限节点列表
     * @return
     */
    private List<TreeSelectVO> getChildTreeSelect(Permission perm, List<Permission> permList) {
        return permList.stream().filter(p -> p.getPid().equals(perm.getId()))
                .map(p -> {
                    TreeSelectVO treeSelectVO = new TreeSelectVO();
                    treeSelectVO.setLabel(p.getTitle());
                    treeSelectVO.setValue(p.getId());
                    List<TreeSelectVO> childTreeSelect = getChildTreeSelect(p, permList);
                    if(org.springframework.util.CollectionUtils.isEmpty(childTreeSelect)) {
                        treeSelectVO.setChildren(null);
                        treeSelectVO.setNumber(null);
                    }else {
                        treeSelectVO.setChildren(childTreeSelect);
                        treeSelectVO.setNumber(childTreeSelect.size());
                    }
                    return treeSelectVO;
                }).collect(Collectors.toList());
    }

    /**
     * 使用递归算法把无限级菜单权限组织为树形数据结构
     * @param root
     * @param list
     * @return
     */
    /**
     * 递归获取子权限节点
     *
     * @param root 当前权限节点
     * @param permList 所有权限节点列表
     * @return 子权限节点列表
     */
    private List<Permission> getChild(Permission root,List<Permission> list){
        List<Permission> subList = list.stream()
                .filter(perm -> perm.getPid().equals(root.getId()))
                .map(perm -> {
                    List<Permission> childList = getChild(perm, list);// 使用递归算法进行深度遍历
                    if(org.springframework.util.CollectionUtils.isEmpty(childList)) {
                        perm.setChildren(null);
                    }
                    else {
                        perm.setChildren(childList);
                    }
                    return perm;
                })
                .sorted(Comparator.comparingInt(e -> (e.getSort() == null ? 0 : e.getSort()))) //升序排序 值越小越靠前
                .collect(Collectors.toList());
        return subList;
    }

    /**
     * 查询当前节点下所有的子节点集合
     * @param curPerm 当前节点对象
     * @param permList 所有菜单权限集合
     * @return
     */
    private Permission findChildren(Permission curPerm, List<Permission> permList) {
        curPerm.setChildren(Lists.newArrayList()); // []
        for (Permission childPerm : permList) {
            if(childPerm.getPid().equals(curPerm.getId())) {
                if (curPerm.getChildren() == null) {
                    curPerm.setChildren(Lists.newArrayList());
                }
                // 递归算法进行深度遍历
                curPerm.getChildren().add(findChildren(childPerm, permList));
            } // ## end if
        } // # end for
        return curPerm;
    }




    /**
     * 根据角色ID获取权限树
     *
     * @param roleId 角色ID
     * @return 权限树
     */
//    @Override
//    public List<Permission> getPermissionTreeByRoleId(Integer roleId) {
//        // 根据角色ID获取该角色的所有权限
//        List<Permission> permList = permissionMapper.getPermissionsByRoleId(roleId);
//
//        // 获取一级权限节点（即 pid = 0 的节点）
//        List<Permission> rootList = permList.stream()
//                .filter(perm -> perm.getPid() == 0)
//                .sorted(Comparator.comparingInt(e -> (e.getSort() == null ? 0 : e.getSort()))) //升序排序，值越小越靠前
//                .collect(Collectors.toList());
//
//        // 构建权限树
//        rootList.forEach(root -> {
//            // 递归获取当前节点的子节点集合
//            List<Permission> childList = getChild(root, permList);
//            root.setChildren(childList);
//        });
//
//        return rootList;
//    }

    @Override
    public List<Permission> getPermissionTreeByRoleId(Integer roleId) {
        // 根据角色ID获取该角色的所有权限
        List<Permission> permList = permissionMapper.getPermissionsByRoleId(roleId);

        // 获取一级权限节点（即 pid = 0 的节点）
        List<Permission> rootList = permList.stream()
                .filter(perm -> perm.getPid() == 0)
                .sorted(Comparator.comparingInt(e -> (e.getSort() == null ? 0 : e.getSort()))) // 升序排序，值越小越靠前
                .collect(Collectors.toList());

        // 构建两层权限树
        rootList.forEach(root -> {
            // 获取一级节点的子节点集合（第二层）
            List<Permission> childList = permList.stream()
                    .filter(perm -> perm.getPid().equals(root.getId()))
                    .sorted(Comparator.comparingInt(e -> (e.getSort() == null ? 0 : e.getSort()))) // 升序排序
                    .collect(Collectors.toList());

            // 设置子节点集合到一级节点
            root.setChildren(childList);
        });

        return rootList;
    }


}